﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Kobets.Automation.Chimera.Common;

namespace Kobets.Automation.Chimera.Agent
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        protected override void OnBeforeInstall(IDictionary savedState)
        {
            base.OnBeforeInstall(savedState);
            var wowPrefix = (Environment.Is64BitOperatingSystem) ? @"\SysWOW64" : String.Empty;
            var settingsDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + wowPrefix + @"\config\systemprofile\AppData\Local\Kobets";
            
            // fix issue with settings not being removed when reinstalling agent, after adding additional settings
            if (Directory.Exists(settingsDir))
                Directory.Delete(settingsDir, true);
        }

        protected override void OnCommitted(IDictionary savedState)
        {
            base.OnCommitted(savedState);
            // set service as Desktop Interactive
            CommonMethods.SetServiceInteractive(serviceInstaller1.ServiceName);
            // set service to restart when there is a fault
            CommonMethods.SetRecoveryOptions(serviceInstaller1.ServiceName);
            
            try
            {
                // register and install certificate for WCF
                CommonMethods.InstallCertificate(Path.Combine(Context.Parameters["InstallDir"], "ChimeraAgentRoot.cer"), "12345678", StoreName.Root, StoreLocation.LocalMachine);
                CommonMethods.InstallCertificate(Path.Combine(Context.Parameters["InstallDir"], "ChimeraAgent.pfx"), String.Empty, StoreName.My, StoreLocation.LocalMachine);

            }
            catch{}

            CommonMethods.StartService(serviceInstaller1.ServiceName);
        }
    }
}
